// #pragma once
#include "ClientHandle.h"

ClientHandle::ClientHandle(QObject* parent)
    : QObject{parent}
{

}

ClientHandle::ClientHandle(qintptr socketDescriptor, QObject* parent)
    : QObject{parent}
    , client_socketDescriptor(socketDescriptor)
{

}

ClientHandle::~ClientHandle()
{
    client_socket->disconnectFromHost();
    client_socket->close();
    // client_socket->deleteLater();
    delete client_socket;
    delete client_info;
}


QTcpSocket* ClientHandle::get_client_socket()
{
    return client_socket;
}


void ClientHandle::working()
{   // 以下所有代码均是子线程中运行
    qDebug() << "Ok";
    client_socket = new QTcpSocket; // 子线程中创建
    client_socket->setSocketDescriptor(client_socketDescriptor);

    // 保存链连接信息
    client_info = new ClientInfo;
    client_info->client_ip = client_socket->peerAddress();
    client_info->client_port = client_socket->peerPort();
    // qDebug() << client_info->client_ip << client_info->client_port;

    // QVariant varValue = QVariant::fromValue(client_info);
    // if (varValue.canConvert<ConnetInfo>())  // 判断能否转化为相应类型
    // {
    //     ConnetInfo bbb = varValue.value<ConnetInfo>();
    //     qDebug() << bbb.client_ip;
    //     qDebug() << bbb.client_port;
    // }

    // 连接消息发送函数
    connect(client_socket, &QTcpSocket::readyRead, this, &ClientHandle::recv_info_slot);

    // 连接客户断开触发函数
    connect(client_socket, &QTcpSocket::disconnected, this, &ClientHandle::disconnect_slot);
}


void ClientHandle::recv_info_slot()
{
    // qDebug() << client_socket->readAll();
    // while (true);    // 测试是否在主线程

    client_info->current_message = client_socket->readAll();

    // 给主线程发送信号
    emit send_message_to_server_signal(const_cast<ClientInfo*>(client_info));
}


void ClientHandle::disconnect_slot()
{
    emit disconnect_signal(this);
    // this->~ClientHandle();   // 这样写会导致程序崩溃
}


// qint64 ClientHandle::send_message_slot(QByteArray* message)
// {
//     qint64 len = client_socket->write(*message);
//     client_socket->waitForBytesWritten();  // 等待数据发送完成
//     return len;
// }


const ClientInfo* ClientHandle::get_client_info()
{
    return client_info;
}
